<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\User as UserModel;
use think\Db;

/**
 * 排行榜接口
 */
class Rank extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['lists'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];


    public function lists()
    {
        $region = $this->request->param('region');
        $distance = $this->request->param('distance/d');
        $model = Db::name('user_cycling')->alias('a');

        $rank_num = 10;

        $model->join('user b','a.uid=b.id');
        $model->field("a.uid,a.totaldistance,b.name,b.nickname,b.avatar");
        if ($distance) {
            $lng = $this->request->param('lng');
            $lat = $this->request->param('lat');
            if (empty($lng) || empty($lat)){
                $this->error(__('Invalid parameters'));
            }
            $model->whereRaw("st_distance_sphere(point(b.lng,b.lat),point($lng,$lat))/1000 <= $distance");
        }
        if ($region) {
            //$region = explode(",", $region);
            
            $model->where('b.region','like','%'.$region.'%');
        }
        $user_id = $this->auth->id ?? 0;
        $model->whereOr('b.id',$user_id);
        $model->order('a.totaldistance', 'desc');
        //$model->limit($rank_num);
        $list = $model->select();
        $str="/http[s]?:\\/\\/[\\w.]+[\\w\\/]*[\\w.]*\\??[\\w=&\\+\\%]*/is";
        $my_rank = [];
        $i = 0;
        if (!empty($list)) {
            foreach ($list as &$item) {
                if(!preg_match($str, $item['avatar']))
                { 
                    $item['avatar'] = !empty($item['avatar'])?cdnurl($item['avatar'], true):cdnurl('/assets/img/avatar2.png', true);
                }
                
                if (!$item['name']) {
                    $item['name'] = 'Emojo'.$item['uid'];
                }
                $item['totaldistance'] = floatval(sprintf("%.1f", $item['totaldistance']* 0.00062137));
                $item['rank'] = ++$i;
                unset($item['nickname']);


                if ($item['uid'] == $user_id) {
                    $my_rank = $item;
                    $my_rank['totaldistance'] = $my_rank['totaldistance'].'miles';
                }
            }
            unset($item);
        }

        if ($user_id&&empty($my_rank)) {

            $user = $this->auth->getUser();
           $model->alias('a')
            ->join('user b','a.uid=b.id');
            if ($region) {
                //$region = explode(",", $region);
                
                $model->where('b.region','like','%'.$region.'%');
            }
            $model->where('a.uid', $user_id);
            $model->field("a.totaldistance");
            $my_total_distance = $model->value('a.totaldistance', '0');
            $rank = count($list)+1;
            if(!preg_match($str, $user['avatar']))
            {
                $avatar = !empty($user['avatar'])?cdnurl($user['avatar'], true):cdnurl('/assets/img/avatar2.png', true);
            }else{
                $avatar = $user['avatar'];
            }
            $list[count($list)] = [
                'uid' => $user_id,
                'name' => empty($user['name']) ? 'Emojo'.$user['uid'] : $user['name'],
                'avatar' => $avatar,
                'totaldistance' => floatval(sprintf("%.1f",$my_total_distance * 0.00062137)),
                'rank' => count($list)+1
            ];
            $my_rank = [
                'uid' => $user_id,
                'name' => empty($user['name']) ? 'Emojo'.$user['uid'] : $user['name'],
                'avatar' => $avatar,
                'totaldistance' => floatval(sprintf("%.1f",$my_total_distance * 0.00062137)).'miles',
                'rank' => $rank
            ];
        }
        $list = array_slice($list, 0, $rank_num);
        $data = compact('list', 'my_rank');
        $this->success(__('成功'), $data);
    }


}
